`
The output now prints the IP address and its open ports on the
same line. Nmap has additional format output options such as the -
oX (XML) output, try to put together a one liner bash script that
extracts open ports from an XML output. Open ports in an XML
output of Nmap look like the following:
$ nmap -iL 172-160-10-hosts.txt --open -oX -
--snip--
<port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="0"/><service
name="ssh" method="table" conf="3"/></port>
--snip--
Exercise 5: Detecting a New Open Port on a Given Host
What if we wanted to monitor a host until it opened a certain
port? You may find this useful if you’re testing an environment in
which hosts come up and down frequently. We can do this quite
easily with a while loop. In Listing 4-13, we continuously check
whether a port is open, waiting five seconds between each execution.
Once we find an open port, we pass this information to Nmap to
perform a service discovery and write the output to a file.
#!/bin/bash
RUST_SCAN_BIN="/home/kali/tools/RustScan/target/release/rustscan"
LOG_FILE="watchdog.log"
IP_ADDRESS="$1"
WATCHED_PORT="$2"
service_discovery(){
local host
local port
host="${1}"
port="${2}"
nmap -sV -p "${port}" "${host}" >> "${LOG_FILE}" 1
}
2 while true; do
3 port_scan=$("${RUST_SCAN_BIN}" -a "${IP_ADDRESS}" -g -p "${WATCHED_PORT}")
4 if [[ -n "${port_scan}" ]]; then
echo "${IP_ADDRESS} has started responding on port ${WATCHED_PORT}!"
echo "Performing a service discovery..."
5 if service_discovery "${IP_ADDRESS}" "${WATCHED_PORT}"; then
echo "Wrote port scan data to ${LOG_FILE}"
break
fi
else
echo "Port not yet open or was closed, sleeping for 5 seconds..."
6 sleep 5
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks